package com.example.beat_x3.Fragments;

import android.annotation.SuppressLint;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.beat_x3.Adapter.ChatAdapter;
import com.example.beat_x3.Client.HandleChats;
import com.example.beat_x3.Client.NotificationHelper;
import com.example.beat_x3.R;

import java.util.ArrayList;

import Entity.Chat;
import Entity.Inf;

public class ChatFragment extends MyFragment {
    ArrayList<String> message = new ArrayList<>();
    ArrayList<Boolean> sender = new ArrayList<>();
    ChatAdapter chatAdapter;
    String opposite;
    RecyclerView contentView;
    TextView prompt;
    Animation fadeInAnimation = AnimationUtils.loadAnimation(Inf.context, R.anim.fade_in);
    LinearLayoutManager l = new LinearLayoutManager(Inf.context, LinearLayoutManager.VERTICAL, false);
    private final Handler myHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                chatAdapter.refresh();
                scroll();
            }
            else {
                scroll();
                prompt.setAlpha(1);
                prompt.startAnimation(fadeInAnimation);
            }
        }
    };

    public ChatFragment(String opposite) {
        this.opposite = opposite;
    }

    @SuppressLint("ClickableViewAccessibility")
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_chat, null);
        view.findViewById(R.id.chat_backbutton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeFragment(Inf.contactFragment);
            }
        });
        View bottomView = view.findViewById(R.id.constraintLayout2);
        bottomView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @NonNull
            @Override
            public WindowInsets onApplyWindowInsets(@NonNull View v, @NonNull WindowInsets insets) {
                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) bottomView.getLayoutParams();
                if (insets.isVisible(WindowInsets.Type.ime())) {
                    params.bottomMargin = insets.getInsets(WindowInsets.Type.ime()).bottom - 60;
                } else {
                    params.bottomMargin = 0;
                }
                bottomView.setLayoutParams(params);
                return insets;
            }
        });
        prompt = view.findViewById(R.id.chat_prompt);
        Button send = view.findViewById(R.id.chat_send);
        EditText word = view.findViewById(R.id.chat_text);
        TextView oppositeName = view.findViewById(R.id.opposite);
        oppositeName.setText(opposite);

        contentView = view.findViewById(R.id.chat_content);
        contentView.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN) {
                    prompt.setAlpha(0);
                }
                return true;
            }
        });

        chatAdapter = new ChatAdapter(message, sender);
        contentView.setLayoutManager(l);
        contentView.setAdapter(chatAdapter);
        l.setStackFromEnd(true);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (word.length() != 0 && word.length()<=100) {
                    String s = word.getText().toString();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HandleChats.uploadChat(opposite, Inf.stuInf.StudentAccount, s);
                        }
                    }).start();
                    message.add(s);
                    sender.add(false);
                    myHandler.sendEmptyMessage(0);
                }
            }
        });
        new InitThread().start();
        new RefreshThread().start();
        return view;
    }

    class InitThread extends Thread {
        @Override
        public void run() {
            ArrayList<Chat> res = HandleChats.getResult(Inf.stuInf.StudentAccount, opposite);
            if (res != null) {
                for (Chat x : res) {
                    message.add(x.word);
                    sender.add(x.st);
                }
                myHandler.sendEmptyMessage(0);
            }
        }
    }

    class RefreshThread extends Thread {
        @Override
        public void run() {
            while (Inf.isLog) {
                ArrayList<Chat> res = HandleChats.refresh(Inf.stuInf.StudentAccount, opposite);
                if (res != null) {
                    for (Chat x : res) {
                        message.add(x.word);
                        sender.add(x.st);
                    }
                    NotificationHelper.showNotification(Inf.context, opposite, "新的消息");
                    myHandler.sendEmptyMessage(1);
                }
                try {
                    sleep(6666);
                } catch (Exception e) {
                }
            }
        }
    }

    private void scroll() {
        if (contentView != null) {
            int lastVisibleItemPosition = l.findLastVisibleItemPosition();
            int itemCount = contentView.getAdapter().getItemCount();
            if (lastVisibleItemPosition != itemCount - 1) {
                contentView.scrollToPosition(itemCount - 1);
            }
        }
    }
}
